<?php
require __DIR__ .'/config.php';
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>客服</title>
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="bower_components/vue/vue.js"></script>
    <script src="dist/js/rongcloud/RongIMLib-2.2.6.min.js"></script>
    <script src="dist/js/rongcloud/RongEmoji-2.2.4.min.js"></script>
    <script src="dist/js/rongcloud/RongIMVoice-2.2.4.min.js"></script>
    <script>window.MainServer = '<?=MainServer?>';</script>
    <script src="dist/js/common.js"></script>
    <?php require __DIR__.'/layout/init.htm'?>
    <style>
        #alerts-container{position: fixed}
        .client-list{margin:0;padding:0}
        .client-list>li{list-style:none;padding:0 10px;height:32px;line-height:32px;}
    </style>
</head>
<body>

<div class="container-fluid" id="service-app">

    <div class="row">
        <div class="col-md-6 col-md-offset-4">
            <div id="alerts-container" style="display: none">
                <div>
                    <div class="alert success alert-success alert-dismissible">
                        <strong>操作成功！<span class="msg-text"></span></strong>
                    </div>
                    <div class="alert error alert-danger alert-dismissible">
                        <strong>操作失败！<span class="msg-text"></span></strong>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h3>客服 <small>{{admin.realname}} <i>在线</i></small></h3>
            <hr>
        </div>
    </div>

    <div class="row" v-show="show.login">
        <div class="col-md-4 col-md-offset-4">
            <h4>客服人员登录</h4>
            <div class="form">
                <div class="form-group">
                    <label>帐号：</label>
                    <input class="form-control" v-model="user.account">
                </div>

                <div class="form-group">
                    <label>密码：</label>
                    <input class="form-control" v-model="user.password" type="password">
                </div>

                <div class="form-group">
                    <button class="btn btn-primary" @click="login">登录</button>
                </div>

            </div>
        </div>
    </div>

    <div class="row" v-show="show.chat">
        <div class="col-md-8 col-md-offset-2">
            <div class="col-md-2">
                <h4>{{chatWindows.length}}</h4>
                <ul class="client-list">
                    <li v-for="(cw,i) in chatWindows" @click="switchWindow(i)">
                        <a><img :src="cw.avatar"></a>
                        <span>{{cw.name}}</span>
                    </li>
                </ul>
            </div>
            <div class="col-md-10">
                <ul class="chat-windows">
                    <li v-for="(cw,i) in chatWindows" v-show="cw.active">
                        <div class="chat-form">
                            <div class="message-head"></div>
                            <div class="message-box"></div>
                            <div class="message-editor"></div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </div>

</div>

<script>



    function ChatWindow(id, name, avatar) {
        this.id = id;
        this.name = name;
        this.avatar = avatar;
        this.active = true;
        this.messageList = [];
        this.messageEdit = '';
        this.rank = 0;
    }

    var serviceApp = new Vue({
        el: '#service-app',
        data: {
            user: {
                account: '',
                password: ''
            },
            admin: {},
            chat: {},
            chatWindows: [],
            show: {
                login: false,
                chat: true
            }
        },
        created: function () {

            init(function (message) {
                console.log(message);
            });

        },
        methods: {
            login: function () {

                ajaxLogin(this.user, function (admin) {
                    this.admin = admin;
                    this.getChat();
                    this.showItem('login');
                }.bind(this), function (resp) {
                    console.log("error: ",resp);
                });

            },
            getChat: function () {
                ajax({
                    uri: '/account/customer_service_login',
                    data: {},
                    success: function (resp) {
                        this.chat = resp.chat;
                        console.log(this.chat);
                        connect(this.chat.token, function () {
                            showAlert('success', '连接成功！');
                        }.bind(this));
                    }.bind(this)
                });
            },
            showItem: function (field) {
                for (let f in this.show) {
                    this.show[f] = (field === f);
                }
            },
            sortWindow: function () {
                this.chatWindows.sort(function (a, b) {
                    return (a.rank > b.rank);
                })
            },
            switchWindow: function (index) {
                this.chatWindows.forEach(function (w, i) {
                    w.active = (index == i);
                });
            },
            groupMessage: function (message) {
                if (RongIMLib.ConversationType.PRIVATE == message.conversationType &&
                        message.targetId == this.chat.id
                ) {
                    let senderUserId = message.senderUserId;
                    let sentTime = message.sentTime;
                    let offLineMessage = message.offLineMessage;

                    let content = this.viewMessage(message);
                }
            },
            viewMessage: function (message) {
                switch(message.messageType){
                    case RongIMClient.MessageType.TextMessage:
                        /*
                         显示消息方法：
                         消息里是 原生emoji
                         RongIMLib.RongIMEmoji.emojiToHTML(message.content.content);
                         */
                        break;
                    case RongIMClient.MessageType.VoiceMessage:
                        /*
                         引入SDK并初始化请参考文档 http://www.rongcloud.cn/docs/web.html#声音库

                         api文档： http://www.rongcloud.cn/docs/api/js/VoiceMessage.html

                         var audio = message.content.content //格式为 AMR 格式的 base64 码
                         var duration = message.content.duration;

                         RongIMLib.RongIMVoice.preLoaded(audio,function(){
                         RongIMLib.RongIMVoice.play(audio,duration);
                         });
                         */
                        break;
                    case RongIMClient.MessageType.ImageMessage:
                        // message.content.content => 图片缩略图 base64。
                        // message.content.imageUri => 原图 URL。
                        break;
                    case RongIMClient.MessageType.DiscussionNotificationMessage:
                        // message.content.extension => 讨论组中的人员。
                        break;
                    case RongIMClient.MessageType.LocationMessage:
                        // message.content.latiude => 纬度。
                        // message.content.longitude => 经度。
                        // message.content.content => 位置图片 base64。
                        break;
                    case RongIMClient.MessageType.RichContentMessage:
                        // message.content.content => 文本消息内容。
                        // message.content.imageUri => 图片 base64。
                        // message.content.url => 原图 URL。
                        break;
                    case RongIMClient.MessageType.InformationNotificationMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.ContactNotificationMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.ProfileNotificationMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.CommandNotificationMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.CommandMessage:
                        // do something...
                        break;
                    case RongIMClient.MessageType.UnknownMessage:
                        // do something...
                        break;
                    default:
                    // do something...
                }
            }
        }
    });



    function print(msg) {
        console.log(msg);
    }

    function getContent(message) {
        let content = message.content.content;
        if (typeof content === "string") content = JSON.parse(content);
        return content;
    }

    function init(onReceive) {

        let appKey = '<?=ChatAppKey?>';
        // 初始化
        RongIMClient.init(appKey);

        RongIMLib.RongIMEmoji.init();
        RongIMLib.RongIMVoice.init();


        RongIMClient.setConnectionStatusListener({
            onChanged: function (status) {
                switch (status) {
                    case RongIMLib.ConnectionStatus.CONNECTED:
                        print('链接成功');
                        break;
                    case RongIMLib.ConnectionStatus.CONNECTING:
                        print('正在链接');
                        break;
                    case RongIMLib.ConnectionStatus.DISCONNECTED:
                        print('断开连接');
                        break;
                    case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                        print('其他设备登录');
                        break;
                    case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                        print('域名不正确');
                        break;
                    case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                        print('网络不可用');
                        break;
                }
            }
        });

        RongIMClient.setOnReceiveMessageListener({
            // 接收到的消息
            onReceived: function (message) {
                // 判断消息类型
                if (typeof message === "function") onReceive(message);
            }
        });
    }

    function connect(token, cb) {
        if (!token) {
            print("token不能为空！");
            return;
        }

        RongIMClient.connect(token, {
            onSuccess: function (userId) {
                cb();
                print(userId + " 登录成功。");
            },
            onTokenIncorrect: function () {
                print('token无效');
            },
            onError: function (errorCode) {
                let info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.UNACCEPTABLE_PROTOCOL_VERSION:
                        info = '不可接受的协议版本';
                        break;
                    case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                        info = 'appkey不正确';
                        break;
                    case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                        info = '服务器不可用';
                        break;
                }
                print(info + " : " + errorCode);
            }
        });
    }

    function join(chatRoomId, cb, err) {
        if (!chatRoomId) return;

        RongIMClient.getInstance().joinChatRoom(chatRoomId, 100, {
            onSuccess: function () {
                // 加入聊天室成功。
                if (typeof cb === "function") cb();
            },
            onError: function (error) {
                // 加入聊天室失败
                if (typeof err === "function") err();
            }
        });
    }

    function getChatRoomInfo(chatRoomId, cb, err) {
        let order = RongIMLib.GetChatRoomType.REVERSE;// 排序方式。
        RongIMClient.getInstance().getChatRoomInfo(chatRoomId, 10, order, {
            onSuccess: function (chatRoom) {
                // chatRoom => 聊天室信息。
                // chatRoom.userInfos => 返回聊天室成员。
                // chatRoom.userTotalNums => 当前聊天室总人数。
                if (typeof cb === "function") cb();
            },
            onError: function (error) {
                // 获取聊天室信息失败。
                if (typeof err === "function") err();
            }
        });
    }

    /**
     *  发送消息
     * @param type
     * @param sendMsg
     * @param cb
     * @param err
     */
    function send(type, sendMsg, cb, err) {

        let s = sendMsg.content;
        let msg = new RongIMLib.TextMessage({content: JSON.stringify(s), extra: "ext"});

        RongIMClient.getInstance().sendMessage(type, sendMsg.receiver, msg, {
            onSuccess: function (message) {
                //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                let content = getContent(message);
                if (typeof cb === "function") cb(content);
            },
            onError: function (errorCode, message) {
                let info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    default :
                        info = "";
                        break;
                }
                console.log('发送失败:' + info);
                if (typeof err === "function") err(errorCode, info);
            }
        });
    }

</script>

</body>
</html>